<template>
	<slot></slot>
	<wd-toast />
	<wd-notify />
	<wd-message-box></wd-message-box>
	<imPortantToast ref="imPortantToastRef"></imPortantToast>
	<voiceCallWaiting ref="voiceCallWaitingRef"></voiceCallWaiting>
	<wd-popup v-model="authPopup" position="bottom" custom-style="border-radius: 25rpx 25rpx 0 0;" @close="handleClose"
		:safe-area-inset-bottom="true">
		<view class="body">
			<view class="title">
				<image class="icon" src="@/static/logo.png"></image>
				{{ appBaseInfo.appName }}
			</view>
			<view class="desc">请您允许授权手机号，方便我们帮您注册账号</view>
			<view class="footer">
				<wd-button type="success" open-type="getPhoneNumber" @getphonenumber="getphonenumber"
					custom-class="wd-button-custom-class-my-success wd-button-custom-class-w100">允许授权</wd-button>

			</view>
		</view>
	</wd-popup>

	<!-- <im-portant-toast /> -->
</template>
<script lang="ts">
	export default {
		name: "app-page"
	}
</script>
<script lang="ts" setup>
	import {
		ref, nextTick,
	} from 'vue';
	import {
		onShow, onUnload
	} from '@dcloudio/uni-app';
	import {
		useToast,
	} from '@/uni_modules/wot-design-uni'
	import {
		useNotify
	} from '@/uni_modules/wot-design-uni/components/wd-notify'
	import {
		useMessage
	} from '@/uni_modules/wot-design-uni'
	import {
		useUserStore,
		useImStore,
		useVoiceCallStore
	} from "@/store"
	import imPortantToast from "@/components/im-portant-toast/im-portant-toast"
	import voiceCallWaiting from "@/components/voice-call-waiting/voice-call-waiting"
	import useRouter from '../../hooks/useRouter';


	const router = useRouter();
	const authPopup = ref(false);
	const userStore = useUserStore(); // 用户信息存储，用于存储用户信息。
	const imStore = useImStore(); // 用户信息存储，用于存储用户信息。
	const voiceCallStore = useVoiceCallStore();
	const imPortantToastRef : any = ref(null);


	const voiceCallWaitingRef : any = ref(null)
	const page = getCurrentPages();
	const message = useMessage()
	const toast = useToast(); // 注册全局弹框组件，用于全局提示信息展示。
	const notify = useNotify()
	uni.$wdToast.init(page[page.length - 1].route, {
		appToast: toast,
		appNotify: notify,
		appMessage: message,
	}); // 初始化全局弹框组件，用于全局提示信息展示。
	const appBaseInfo = uni.getAppBaseInfo();
	const openid = ref(null)
	const timeoutId : any = ref(null);

	onShow(() => {
		if (!userStore.token && page[page.length - 1].route != 'commonPage/register/register' &&
			page[page.length - 1].route != 'commonPage/login/login') {
			userStore.wxLogin();
		}
		if (page[page.length - 1].route == 'pages/my/my' || page[page.length - 1].route == 'pages/im/im' || page[page.length - 1].route == 'pages/lawyer/lawyer' || page[page.length - 1].route == 'pages/index/index') {
			if (!voiceCallStore.isCallIng) {
				uni.showTabBar();
			}
		}
	})
	onUnload(() => {
		voiceCallStore.stopVoiceCallAudio();
		uni.$emit('on-im-portant-toast-close')
		uni.$emit('on-clear-timeout-id')
		voiceCallStore.editCallStoreData({
			isCallIng: false,
		});
	})
	const getphonenumber = async (e : any) => {
		console.log(e)
		if (e.errMsg === 'getPhoneNumber:fail user deny') {
			userStore.setIsWxLogining(false);
		}
		uni.login({
			provider: 'weixin', //使用微信登录
			success: async (loginRes) => {
				let res : any = await userStore.wxPhone({
					code: loginRes.code,
					encryptedData: e.encryptedData, // 授权弹框的openid。
					iv: e.iv,
				});
				console.log(res, 'res', {
					openid: openid.value,
					phone: res.phone,
					step: 2,
				})
				router.push({
					url: "/commonPage/register/register",
					params: {
						openid: openid.value,
						phone: res.phone,
						step: 2,
					},
				});
				handleClose();
				// res = await userStore.wxSaveInfo({
				// 	openid: openid.value,
				// 	phone: res.phone,
				// 	yzm: '123456',
				// 	password: '123456',
				// 	repassword: '123456',
				// });
				// userStore.setToken(res.token, res.user_id);
				// userStore.isWxLogining = false;
				// handleClose();
				// uni.pageReLoad();


			}
		});

	}
	const showAuthPopup = (wxopenid : any) => {
		console.log(wxopenid, 'wxopenid')
		if (wxopenid) {
			openid.value = wxopenid; // 设置授权弹框的openid。
		}
		authPopup.value = true; // 显示授权弹框，用于授权提示信息展示。
	};
	uni.pageReLoad = () => {
		// 声明一个pages使用getCurrentPages方法
		const curPage = page[page.length - 1]
		// 声明一个当前页面
		curPage.onLoad(curPage.options) // 传入参数
		curPage.onShow()
		curPage.onReady()
	}

	uni.$on('on-show-auth-popup', (data : any) => {
		showAuthPopup(data);
	})
	const handleClose = () => {
		authPopup.value = false; // 关闭授权弹框，用于授权提示信息展示。
		userStore.setIsWxLogining(false);
	}
	// 初始化 提示音
	voiceCallStore.initVoiceCallAudioContext();
	const voiceCallOutTime = (data : any, voiceCallInfo : any, text = "无答应") => {
		if (timeoutId.value == null) {
			return false;
		}
		// 超过接听时长 提示 超时 关闭
		if (data.in == false && voiceCallStore.isCallIng) {
			let sendData = {
				data: 'voice-call',
				description: '',
				extension: JSON.stringify({
					roomId: voiceCallInfo.roomId,
					text: text,
					show: 'true'
				})
			}
			imStore.sendMessage(sendData, 'custom', data.to);
		} else if (voiceCallStore.isCallIng) {
			uni.$emit('on-im-portant-toast-close')
		}
		uni.$emit('on-voice-call-end')
	}
	// 呼叫结束
	uni.$on('on-voice-call-end', (data : any) => {
		uni.$emit('on-voice-call-exit-room', 1)
		uni.$emit('on-im-portant-toast-close')
		uni.$emit('on-clear-timeout-id')
		voiceCallStore.stopVoiceCallAudio();
		voiceCallStore.editCallStoreData({
			isCallIng: false,
		});
	})

	uni.$on('on-clear-timeout-id', (data : any) => {
		clearTimeout(timeoutId.value);
		timeoutId.value = null;
	})

	// TODO 需要兼容 发起人和接听人 
	uni.$on('on-voice-call', (data : any) => {
		if (voiceCallStore.isCallIng) {
			return false;
		}
		let voiceCallRoomInfo = JSON.parse(data.payload.extension);
		if (data.in) {
			uni.$emit('on-im-portant-toast-show', voiceCallRoomInfo)
		}
		voiceCallStore.editCallStoreData({
			currentCall: voiceCallRoomInfo,
			isCallIng: true,
		});
		voiceCallStore.playVoiceCallAudio();
		let newDateTime = new Date().getTime();
		let timeout = voiceCallRoomInfo.deadline - newDateTime;
		timeout = timeout > 0 ? timeout : 0
		timeoutId.value = setTimeout(() => {
			voiceCallOutTime(data, voiceCallRoomInfo);
		}, timeout)
	})
</script>

<style lang="less" scoped>
	.body {
		padding: 20rpx 24rpx; // 设置底部按钮的间距。

		.title {
			font-size: 36rpx; // 设置标题字体大小。
			font-weight: bold; // 设置标题字体粗细。
			margin-bottom: 12px; // 设置标题与描述之间的间距。
			display: flex; // 设置标题的布局方式为flex，以便实现两列布局。
			align-items: center; // 设置标题的垂直居中对齐方式。

			.icon {
				width: 60rpx; // 设置图标宽度。
				height: 60rpx; // 设置图标高度。
				margin-right: 12px; // 设置图标与标题之间的间距。

			}
		}

		.desc {
			font-size: 28rpx; // 设置描述字体大小。
			margin-bottom: 12px; // 设置标题与描述之间的间距。
		}

		.footer {
			display: flex; // 设置底部按钮的布局方式为flex，以便实现两列布局。
			justify-content: space-between; // 设置底部按钮的间距。


			.btn {
				width: 45% !important; // 设置按钮的宽度为40%。
			}
		}
	}
</style>